<template>
  <div class="layout-container">
    <el-card shadow="always" class="card">
      <el-divider content-position="left">第三步 上传正确代码</el-divider>
      <div class="header-container">
        <el-select v-model="selectedLanguage" @change="updateLanguage" class="select" size="default">
          <el-option
              v-for="option in options"
              :key="option.value"
              :label="option.label"
              :value="option.value">
          </el-option>
        </el-select>
      </div>
      <el-divider/>
      <div ref="editContainer" class="code-editor"></div>
      <el-divider/>
      <el-button size="large" class="next3" type="primary" @click="submitForm">完成</el-button>
    </el-card>
  </div>
</template>

<script setup>
import { getCurrentInstance,ref, onMounted, nextTick, computed } from 'vue';
import * as monaco from 'monaco-editor/esm/vs/editor/editor.main.js';
import JsonWorker from 'monaco-editor/esm/vs/language/json/json.worker?worker';
import axios from "axios";
import { API_BASE_URL, AUTH_TOKEN } from '@/config.ts';
import { ElMessage } from "element-plus";
import router from '@/router';
import { useStore } from "vuex";
import { defineProps, defineEmits } from 'vue';
import {useRoute} from "vue-router";

// 定义props
const props = defineProps({
  value: String
});

// 定义事件发射器
const emit = defineEmits(['update:value']);


let problemId = null;
let testGroupMongoId = null;
let testGroupId = null;
const {proxy} = getCurrentInstance();


// Monaco Editor 全局环境配置
self.MonacoEnvironment = {
  getWorker() {
    return new JsonWorker();
  },
};

const selectedLanguage = ref('C++');
const showInput = ref(false);
const inputContent = ref('');
let monacoEditor = null;
const route = useRoute();
// 初始化 Monaco Editor
onMounted(async () => {

  const editing=route.query.editing;
  const pId=route.query.problemId;
  console.log(editing)
  console.log(pId)
  if(editing==='1'){
    problemId=route.query.problemId;
    testGroupMongoId=route.query.updateTestGroupMongoId;
    testGroupId=route.query.updateTestGroupId;
    const url = `${API_BASE_URL}/ProblemsGroup/problems/code/${pId}`;
    const response = await axios.get(url, {
      headers: {
        'token': AUTH_TOKEN
      }
    });
    if(response.data.code===200){
      const languageMap = {
        "C++": "cpp",
        "Java": "Java",
        "Python3": "python",
        "C": "c",
      };
      // 根据选择的语言获取对应的格式
      const lgg = languageMap[response.data.data.language] || 'cpp';
      selectedLanguage.value=response.data.data.language;
      monacoEditor = monaco.editor.create(proxy.$refs.editContainer, {
        value: response.data.data.code,
        readOnly: false,
        language: lgg,
        theme: 'vs',
        selectOnLineNumbers: true,
        renderSideBySide: false,
      });
    }else{
      console.error(response.data.msg);
    }
  }else{
    problemId=route.query.problemId;
    testGroupMongoId=route.query.testGroupMongoId;
    testGroupId=route.query.testGroupId;
    console.log("23232323")
    console.log(problemId)
    console.log(testGroupMongoId)
    console.log(testGroupId)
    await nextTick();
    monacoEditor = monaco.editor.create(proxy.$refs.editContainer, {
      value: props.value || '',
      readOnly: false,
      language: selectedLanguage.value,
      theme: 'vs',
      selectOnLineNumbers: true,
      renderSideBySide: false,
    });
  }
  monacoEditor.onDidChangeModelContent(() => {
    const currentValue = monacoEditor?.getValue();
    emit('update:value', currentValue);
  });
});

// 切换输入显示
const toggleInput = () => {
  showInput.value = !showInput.value;
};

// 提交表单
const submitForm = async () => {
  const language = selectedLanguage.value === "cpp" ? "C++" : selectedLanguage.value;
  const postData = {
    testGroupMongoId: testGroupMongoId,
    testGroupId: testGroupId,
    problemId: problemId,
    code: monacoEditor.getValue(),
    language: language
  };

  try {
    const response = await axios.post(`${API_BASE_URL}/ProblemsGroup/problems/uploadCode`, postData, {
      headers: {'token': AUTH_TOKEN}
    });
    if (response.data.code !== 200) {
      ElMessage.error(response.data.msg);
    } else {
      await router.push('/Manager');
    }
  } catch (error) {
    ElMessage.error('Network or server error');
  }
};

// 语言选项和更新函数
const options = [
  {label: "C++", value: 'C++'},
  {label: 'JavaScript', value: 'javascript'},
  {label: 'Python3', value: 'Python3'},
  {label: 'Java', value: 'java'}
];
const updateLanguage = () => {
  monaco.editor.setModelLanguage(monacoEditor.getModel(), selectedLanguage.value);
};
</script>


<style scoped>
.next3 {
  margin-top: 20px;
  margin-bottom: 20px;
  float: right;
}

.code-editor {
  height: 20vh;
}

.header-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.select {
  width: 100px;
}
</style>